<script setup lang="ts">
import page from "./index";
import pageUser from "@/views/careful-ui/system/user/index";
import {
  create,
  exportExcel,
  deleteById,
  batchDelete,
  update,
  listTree,
  getById
} from "@/apis/careful-ui/system/dept";
import {
  listPage as userListPage
} from "@/apis/careful-ui/system/user"
import {skyMsgError, skyNoticeError, skyNoticeSuccess} from "@/utils/sky";

const skyDrawerRef = ref();
const skyWindowRef = ref();
const formRef = ref();

const pageData = reactive({
  ...page.pageData,
});
const method = reactive({
  /** 搜索 */
  handleSearch: () => {
    method.handleListPage();
  },
  /** 重置 */
  resetSearch: () => {
    method.resetSearchParams();
    method.handleListPage();
  },
  /** 重置搜索参数 */
  resetSearchParams: () => {
    pageData.pageParams.creator = null;
    pageData.pageParams.modifier = null;
    pageData.pageParams.page = 1;
    pageData.pageParams.pageSize = 10;
    pageData.pageParams.status = true;
    pageData.pageParams.name = "";
    pageData.pageParams.code = "";
  },

  /** 添加 */
  handleAdd: () => {
    // 打开弹出框
    skyDrawerRef.value.skyOpen();
    // 重置表单
    method.handleResetForm();
    // 标题
    pageData.title = "添加";
  },
  /** 清空表单数据 */
  handleResetForm: async () => {
    await nextTick(() => {
      if (formRef.value) {
        // 重置该表单项，将其值重置为初始值，并移除校验结果
        formRef.value.resetFields();
      }
    });
    pageData.form = {
      id: null,
      parent_id: null,
      name: "",
      code: "",
      owner: "",
      phone: "",
      email: "",
      sort: 1,
      status: true,
      remark: null,
    };
  },

  /** 确定  */
  handleConfirm: () => {
    if (!formRef.value) return;
    pageData.confirmLoading = true;
    (formRef.value).validate(async (valid: any) => {
      if (valid) {
        if (pageData.form.id) {
          try {
            await update(pageData.form);
            skyNoticeSuccess("修改成功🌻");
          } catch (error) {
            skyNoticeError("修改失败，请刷新重试🌻");
          }
        } else {
          try {
            await create(pageData.form);
            skyNoticeSuccess("添加成功🌻");
          } catch (error) {
            skyNoticeError("添加失败，请刷新重试🌻");
          }
        }
        pageData.confirmLoading = false;
        skyDrawerRef.value.skyQuickClose();
        await method.handleResetForm();
        await method.handleListPage();
      } else {
        skyMsgError("验证失败，请检查填写内容🌻");
        pageData.confirmLoading = false;
      }
    });
  },
  /** 取消 */
  handleCancel: () => {
    skyDrawerRef.value.skyClose();
  },

  /** 数据表格 */
  handleListPage: async () => {
    try {
      pageData.loading = true;
      pageData.tableList = [];
      const res: any = await listTree(pageData.pageParams);
      pageData.tableList = res.data;
    } catch (error) {
      skyMsgError("数据查询失败，请刷新重试🌻");
    } finally {
      pageData.loading = false;
    }
  },

  /** 开窗 */
  handleButtonClick: (title: any, val: any) => {
    // 打开弹出框
    skyWindowRef.value.skyOpen();
    // 判断参数
    if (title === "负责人") {
      pageData.window.title = "负责人";
      pageData.window.query = pageUser.pageData.pageParams;
      pageData.window.columns = pageUser.pageData.tableWindowColumns;
      pageData.window.method = userListPage;
    }
  },
  /** 选择指定来源参数 */
  handleWindowConfirm: (val: any) => {
    if (pageData.window.title === "负责人") {
      pageData.form.owner = val.username;
      pageData.form.email = val.email;
      pageData.form.phone = val.mobile;
    }
    pageData.window = {
      title: "",
      query: {},
      columns: [],
      method: (params: any) => Promise,
    };
    skyWindowRef.value.skyQuickClose();
  },
  /** 取消来源参数 */
  handleWindowCancel: () => {
    skyWindowRef.value.skyClose();
  },
});
onMounted(() => {
  method.handleListPage();
});
</script>

<template>
  <div class="sky-flex">
    <SkyCard>
      <!-- 搜索条件 -->
      <el-form v-show="pageData.showSearch" :inline="true" label-width="70px">
        <el-form-item label="部门名称">
          <el-input
            style="width: 160px"
            placeholder="部门名称"
            v-model="pageData.pageParams.name"
            clearable
            @keyup.enter.native="method.handleSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门编码">
          <el-input
            style="width: 160px"
            placeholder="部门编码"
            v-model="pageData.pageParams.code"
            clearable
            @keyup.enter.native="method.handleSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="pageData.pageParams.status" style="width: 160px" clearable>
            <el-option label="启用" :value="true"/>
            <el-option label="禁用" :value="false"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-throttle="method.handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-debounce="method.resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" icon="plus" plain @click="method.handleAdd">新增</el-button>
        </el-col>
      </el-row>
      <br/>
      <!-- 数据表格 -->
      <el-table
        v-loading="pageData.loading"
        border
        stripe
        row-key="id"
        :data="pageData.tableList"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        empty-text="暂时没有数据哟🌻"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left"/>
<!--        <el-table-column label="主键ID" prop="id" width="110" align="center" sortable :show-overflow-tooltip="true"/>-->
        <el-table-column label="部门名称" prop="name" width="200" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="部门编码" prop="code" width="150" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="负责人" prop="owner" width="150" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="联系电话" prop="phone" width="150" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="邮箱" prop="email" width="150" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="上级部门" prop="parent_id" width="150" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="排序" prop="sort" width="100" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="状态" prop="status" width="150" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              class="ml-2"
              inline-prompt
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              active-text="启用"
              inactive-text="禁用"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" width="200" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="创建人" prop="creator" width="150" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="修改人" prop="modifier" width="150" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="创建时间" prop="createTime" width="180" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="修改时间" prop="updateTime" width="180" align="center" sortable :show-overflow-tooltip="true"/>


        <el-table-column v-if="false" label="数据归属部门" prop="belong_dept" width="170" align="center"
                         :show-overflow-tooltip="true">
          <template #default="scope">
            {{ useSkyDeptObj(skyDept.dept, scope.row.belong_dept) }}
          </template>
        </el-table-column>


        <el-table-column v-if="false" label="操作" align="center" width="120" fixed="right">
          <template #default="{ row }">
            <el-tooltip content="修改🌻" placement="top">
              <el-button
                type="primary"
                icon="Edit"
                circle
                plain
                @click="method.handleUpdate(row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除🌻" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="method.handleDelete(row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加 OR 修改 -->
      <SkyDrawer
        ref="skyDrawerRef"
        :title="pageData.title"
        @skyConfirm="method.handleConfirm"
        @skyCancel="method.handleCancel"
        :loading="pageData.confirmLoading"
      >
        <template #content>
          <el-form ref="formRef" :rules="pageData.rules" :model="pageData.form" label-width="83px" status-icon>
            <cf-select-tree
              :sm="24"
              label="上级部门"
              prop="parent_id"
              :model="pageData.form"
              node-key="id"
              :data="pageData.tableList"
              :props="{children: 'children', label: 'name'}"
            />
            <cf-input
              :sm="24"
              label="部门名称"
              prop="name"
              :model="pageData.form"
            />
            <cf-input
              :sm="24"
              label="部门编号"
              prop="code"
              :model="pageData.form"
            />
            <cf-input-icon
              :sm="24"
              label="负责人"
              prop="owner"
              :model="pageData.form"
              @button-click="method.handleButtonClick('负责人', null)"
            />
            <cf-input
              :sm="24"
              label="联系电话"
              prop="phone"
              :model="pageData.form"
              :disabled="true"
            />
            <cf-input
              :sm="24"
              label="邮箱"
              prop="email"
              :model="pageData.form"
              :disabled="true"
            />
            <cf-input-number
              :sm="24"
              label="排序"
              prop="sort"
              :model="pageData.form"
            />
            <cf-input
              :sm="24"
              label="备注"
              prop="remark"
              :type="'textarea'"
              :model="pageData.form"
              :rows="2"
            />
          </el-form>
          {{ pageData.form }}
        </template>
      </SkyDrawer>
      <!-- 来源参数 -->
      <SkyWindow
        ref="skyWindowRef"
        :title="pageData.window.title"
        :columns="pageData.window.columns"
        :fetchMethod="pageData.window.method"
        :queryParams="pageData.window.query"
        @skyConfirm="method.handleWindowConfirm"
        @skyCancel="method.handleWindowCancel"
      />
    </SkyCard>
  </div>
</template>

<style scoped lang="scss">

</style>
